package com.chinamobile.iot.controller;

import com.chinamobile.iot.service.BrokerService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created by szl on 2016/12/7.
 */
@RestController
public class MqttBrokerController {

    private Logger logger = LoggerFactory.getLogger(MqttBrokerController.class);

    @Autowired
    private BrokerService brokerService;


    /**
     * 查询某个终端设备是否在线
     *
     * @param mqttId 设备ID
     * @return 是-success, 否-the device is not online
     */
    @ApiOperation(value = "查看设备是否在线")
    @RequestMapping(value = "devices/online", method = RequestMethod.GET)
    public Boolean isOnline(
            @ApiParam(name = "mqttId", value = "设备ID", required = true)
            @RequestParam String mqttId) {

        return brokerService.isOnline(mqttId);
    }

    @ApiOperation(value = "查看在线设备数")
    @RequestMapping(value = "devices/count", method = RequestMethod.GET)
    public int getClientCount() {
        return brokerService.getClientCount();
    }


    @ApiOperation(value = "向设备下发命令")
    @RequestMapping(value = "devices/{mqttId}/cmd", method = RequestMethod.POST)
    public Boolean sendCommand(
            @ApiParam(name = "mqttId", value = "设备ID", required = true)
            @PathVariable("mqttId") String mqttId,
            @ApiParam(name = "commandId", value = "命令ID", required = true)
            @RequestParam("commandId") String commandId,
            @ApiParam(name = "type", value = "命令数据类型,(json, int, double, bin, string)", required = true)
            @RequestParam("type") String type,
            @ApiParam(name = "content", value = "命令内容", required = true)
            @RequestBody String content) {

        return brokerService.sendCommand(mqttId, commandId, type, content);
    }

    /**
     * 强制下线设备
     *
     * @param mqttId 设备ID
     * @return 在线且下线成功返回true，其他返回false
     */
    @ApiOperation(value = "强制下线设备")
    @ApiResponse(code = 200, message = "{data:true}")
    @PostMapping("devices/offline/{mqttId}")
    public Boolean offlineDevice(
            @ApiParam(name = "mqttId", value = "设备ID", required = true)
            @PathVariable String mqttId) {

        return brokerService.offlineDevice(mqttId);
    }
}
